package com.pccw.client.hessianclient;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.io.IOException;


import com.caucho.hessian.client.HessianConnection;
import com.caucho.hessian.client.HessianConnectionFactory;
import com.caucho.hessian.client.HessianProxyFactory;
import com.pccw.client.hessianclient.MyHessionURLConnection.ResponseHeadersParser;

public class MyConnectionFactory implements HessianConnectionFactory {
	protected static Logger log  = Logger.getLogger(MyConnectionFactory.class.getName());
	
	private HessianProxyFactory proxyFactory;
	private String cookie;

	public void setHessianProxyFactory(HessianProxyFactory factory) {
		proxyFactory = factory;
	}
	
	public HessianConnection open(URL url) throws IOException {
		URLConnection conn = url.openConnection();
		long connectTimeout = proxyFactory.getConnectTimeout();
		if (connectTimeout >= 0){
			conn.setConnectTimeout((int) connectTimeout);
		}
		conn.setDoOutput(true);
		long readTimeout = proxyFactory.getReadTimeout();
		if (readTimeout > 0) {
			try {
				conn.setReadTimeout((int) readTimeout);
			} catch (Throwable e) {
			}
		}
		
		MyHessionURLConnection hconn=new MyHessionURLConnection(url, conn,new ResponseHeadersParser(){
			@Override
			public void parse(HttpURLConnection conn) throws IOException {
				String sessionid=MyHessianUtil.proessSetCookie(conn);
				if(sessionid!=null){
					log.log(Level.INFO, "the server give me a cookie:"+sessionid);
					cookie=sessionid;
				}
			}
		});
		if(cookie!=null){
			hconn.addHeader("cookie", cookie);
		}
		return hconn;
	}

		public String getCookie() {
			return cookie;
		}
	
		public void setCookie(String cookie) {
			this.cookie = cookie;
		}
		

}
